import axios from "axios";

import appConfig from "@/config/index";
import { message } from 'ant-design-vue';

// const TOKEN_INVALID = "Token认证失败，请重新登录";
// const NETWORK_ERROR = "网络请求异常，请稍后重试";
const service = axios.create({
  baseURL: appConfig.baseApi,
  timeout: 80000,
});

service.interceptors.request.use((req) => {
  console.log("请求参数:", req);
  const headers = req.headers;
  return req;
});

service.interceptors.response.use((res) => {
  console.log("返回结果:", res);
  const { code, data, message:msg } = res.data;
  if (code == 0) {
    console.log(data);

    message.success(msg);
    return data;
  } else if(code == 1101) {
    message.error(msg)
  }
  else if(code == 1000) {
    message.error(msg)
  }
});

function request(options) {
  options.method = options.method || "get";
  if (options.method.toLowerCase() == "get") {
    options.params = options.data;
  }
  let isMock = appConfig.mock;
  if (typeof options.mock != "undefined") {
    isMock = options.mock;
  }

  if (appConfig.env == "prod") {
    service.defaults.baseURL = appConfig.baseApi;
  } else {
    service.defaults.baseURL = isMock ? appConfig.mockApi : appConfig.baseApi;
  }
  return service(options);
}

["get", "post", "delete"].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options,
    });
  };
});

export default request;
